package com.sinopec.basemodule.resultcontract

import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentResultListener
import androidx.lifecycle.LifecycleOwner
import com.alibaba.android.arouter.launcher.ARouter

/**
 *
 *
 * 一个轮子
 * 设置值获取值 契约 fragment
 *
 */
class UnIdirectionalFragmentContract<Req>(
    val key: String,
    private val getSet: BundleAble<Req>,
) {
    /**
     * 任务-跟进信息列表Fragment
     * 数据接收器
     */
    fun receive(
        fragmentManager: FragmentManager,
        lifecycleOwner: LifecycleOwner,
        onResult: (req: Req?) -> Unit
    ) {
        fragmentManager.setFragmentResultListener(
            key, lifecycleOwner,
            FragmentResultListener { requestKey, result ->
                onResult(getSet.get(result))
            })
    }

    /**
     * 任务-跟进信息列表Fragment
     * 数据发射器
     */
    fun send(
        fragmentManager: FragmentManager,
        req: Req?
    ) {
        val bundle = Bundle()
        getSet.set(req, bundle)
        fragmentManager.setFragmentResult(
            key,
            bundle
        )
    }

}


/**
 * 通过key创建 fragment 这个key必须是arouter的路由路径
 */
fun <Req> UnIdirectionalFragmentContract<Req>.createFragment() = createFragment(key)


fun createFragment(targetPath: String): Fragment {
    return ARouter.getInstance()
        .build(targetPath)
        .navigation()
            as Fragment
}